<template>
  <div class="container dealer-list" v-loading="loading">
    <div class="handle-box">
      <el-input v-model="query.DomainName" placeholder="域名" class="handle-input mr10" maxlength="20"></el-input>
      <el-input v-model="query.TenantName" placeholder="经销商名称" class="handle-input mr10" maxlength="20"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>

      <el-button type="success" :icon="Plus" @click="addDealer">新增经销商</el-button>
      <el-button type="primary" @click="countConsume">消耗统计</el-button>

    </div>

    <el-row>
      <el-table :data="dealers.items" border class="table" :row-key="row => row.id"
                @selection-change="handleSelectionChange" table-layout="auto">
        <el-table-column prop="Username" label="账号"/>
        <el-table-column prop="TenantName" label="经销商名称"/>
        <el-table-column prop="DomainName" label="三级域名"/>
        <el-table-column prop="DatabaseName" label="数据库名称"/>
        <el-table-column prop="TotalCalls" label="剩余会话次数"/>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.Status==2" type="success">正常</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column  prop="create_time"  label="注册时间">
          <!-- <template #default="scope">
            <span>{{ dateFormat(scope.row['created_at']) }}</span>
          </template> -->
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button-group class="ml-4">
              <el-button size="small" type="primary" @click="dealerEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="removeDealer(scope.row)">禁用</el-button>
              <el-button size="small" type="success" @click="resetPass(scope.row)">重置密码</el-button>
              <el-button size="small" type="warning" @click="distribute(scope.row)">分配</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-if="dealers.total > 0"
                       background
                       layout="total, prev, pager, next"
                       v-model:current-page="dealers.page"
                       v-model:page-size="dealers.page_size"
                       :total="dealers.total"
                       @current-change="fetchDealerList(dealers.page, dealers.page_size)"
        />

      </div>
    </el-row>
  
    <el-dialog
        v-model="showDealerEditDialog"
        :title="title"
        :close-on-click-modal="false"
        width="50%"
    >
      <el-form :model="dealer" label-width="120px" ref="dealerEditFormRef" :rules="rules">
        <el-form-item label="租户名称：" prop="TenantName">
          <el-input v-model="dealer.TenantName" autocomplete="off" maxlength="30"/>
        </el-form-item>
        <el-form-item label="三级域名：" prop="DomainName">
          <el-input v-model="dealer.DomainName" autocomplete="off" maxlength="16"/>
        </el-form-item>
        <el-form-item label="数据库名称：" prop="DatabaseName">
          <el-input v-model="dealer.DatabaseName" :disabled="!add"  autocomplete="off" />
        </el-form-item>
        <el-form-item  label="用户名：" prop="Username">
          <el-input v-model="dealer.Username" autocomplete="off" maxlength="16"/>
        </el-form-item>
        <el-form-item  label="密码：" prop="Password">
          <el-input v-model="dealer.Password" autocomplete="off" maxlength="16"/>
        </el-form-item>
        <!-- <el-form-item  label="对话次数" prop="TotalCalls">
          <el-input v-model.number="dealer.TotalCalls" autocomplete="off" maxlength="10"/>
        </el-form-item> -->
        
        <el-form-item label="启用状态">
          <el-switch v-model.number="dealer.Status"   :active-value="parseInt('2')"
          :inactive-value="parseInt('1')"/>
        </el-form-item>
        </el-form>
      <template #footer>
            <span class="dialog-footer">
              <el-button @click="showDealerEditDialog = false">取消</el-button>
              <el-button type="primary" @click="saveDealer">提交</el-button>
            </span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="showResetPassDialog"
        title="重置密码"
        width="50%"
    >
      <el-form label-width="100px" ref="dealerEditFormRef">
        <el-form-item label="账户：">
          <el-input v-model="pass.dealername" autocomplete="off" readonly disabled/>
        </el-form-item>

        <el-form-item label="新密码：">
          <el-input v-model="pass.Password" autocomplete="off"/>
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button type="primary" @click="doResetPass">提交</el-button>
            </span>
      </template>

    </el-dialog>
    <el-dialog
        v-model="showDistributeDialog"
        title="分配"
        width="50%"
    >
      <el-form label-width="100px" ref="userEditFormRef">
        <el-form-item label="账户：">
          <el-input v-model="distributeData.username" autocomplete="off" readonly disabled/>
        </el-form-item>

        <el-form-item label="剩余次数：">
          <el-input v-model="distributeData.calls" autocomplete="off" readonly disabled/>
        </el-form-item>
        <el-form-item >
          <el-radio-group v-model="distributeData.distributeMethod" class="ml-4">
            <el-radio-button :label="1" >
              <el-icon><Plus /></el-icon>
            </el-radio-button>
            <el-radio-button :label="0" >
              <el-icon><Minus /></el-icon>
            </el-radio-button>
          </el-radio-group>

          <el-input style="width: 50%;margin-left: 10px;" v-model.number="distributeData.amount" autocomplete="off" placeholder="请输入分配次数"/> 
          <!-- <div class="distribute-test">可分配次数：{{ allocCalls }}</div> -->
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeDistributeDialog">取消</el-button>
              <el-button type="primary" @click="doDistribute">提交</el-button>
            </span>
      </template>
      </el-dialog> 
    <el-dialog
        v-model="showCountConsumeDialog"
        title="消耗统计"
        width="55%"
    >
    <div class="count-consum-time"> 
      <div class="count-consum-time-picker">查询时间：</div>
    <el-date-picker
        
        v-model="timeRange "
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="YYYY/MM/DD ddd"
        time-format="A hh:mm:ss"
      /></div>
    
      <echarts-box :EchartsData="EchartsData"></echarts-box>
      

    </el-dialog>
  </div>
  
</template>

<script setup>
import {onMounted, reactive, ref,watch} from "vue";
import {httpGet, httpPost} from "@/utils/http";
import {ElMessage, ElMessageBox} from "element-plus";
import {dateFormat, disabledDate, removeArrayItem} from "@/utils/libs";
import {Plus, Search,Minus} from "@element-plus/icons-vue";
import echartsBox from "../../components/superadmin/AdminEcharts.vue"; // 引入 Echarts 组件

// 变量定义
const dealers = ref({page: 1, page_size: 15, items: []})
const query = ref({DomainName: '',TenantName: '', page: 1, page_size: 15})

const title = ref('添加用户')
const vipImg = ref("/images/vip.png")
const add = ref(true)
const user = ref({status: false, restrict: 0})
const dealer = ref({DatabaseName: ''})
const pass = ref({dealername: '', Password: ''})
const roles = ref([])
const models = ref([])
const showDealerEditDialog = ref(false)
const showResetPassDialog = ref(false)
const resetPassword = ref('');
const showDistributeDialog = ref(false) 
const distributeData = ref({username: '', calls: '', id: 0,distributeMethod:"1",amount:""})
const showCountConsumeDialog = ref(false) 
const timeRange  = ref('') 
const EchartsData = ref({})
const rules = reactive({
  TenantName: [
    {required: true, message: '请输入租户名称', trigger: 'blur'},
  ],
  DomainName: [
  { 
    required: true, 
    message: '请输入三级域名', 
    trigger: 'blur' 
  },
  { 
    pattern: /^[a-zA-Z][a-zA-Z0-9]{0,14}$/, 
    message: '三级域名格式为英文开头的十五位内的字母、数字', 
    trigger: 'blur' 
  }
],
DatabaseName: [
  { 
    required: true, 
    message: '请输入数据库名称', 
    trigger: 'blur' 
  },
  { 
    // pattern: /^[a-zA-Z][a-zA-Z0-9_]{0,100}$/, 
    message: '数据库名称格式为英文开头的一百位内的字母、数字、下划线', 
    trigger: 'blur' 
  },
  ],
  Username: [{required: true, message: '账号不能为空', trigger: 'change'}],
  Password: [{required: true, message: '密码不能为空', trigger: 'change'}],
  // TotalCalls: [{required: true, message: '对话次数不能为空', trigger: 'change'}],
})
const loading = ref(true)

const dealerEditFormRef = ref(null)
onMounted(() => {
  fetchDealerList(dealers.value.page, dealers.value.page_size)
  // 获取角色列表
  httpGet('/api/superadmin/role/list').then((res) => {
    roles.value = res.data;
  }).catch(() => {
    ElMessage.error("获取聊天角色失败");
  })
  // getAllocCalls()
    //消耗统计接口
    httpPost('/api/superadmin/tenants/totalCallsCount',{start_time:'2023-01-01 00:00:00',end_time:'2026-01-01 00:00:00'}).then((res) => {
    EchartsData.value = res.data;
  }).catch(() => {
    ElMessage.error("获取消耗统计数据失败");
  })

  httpGet('/api/superadmin/model/list').then(res => {
    models.value = res.data
  }).catch(e => {
    ElMessage.error("获取模型失败：" + e.message)
  })
})

const fetchDealerList = function (page, pageSize) {
  query.value.page = page
  query.value.page_size = pageSize
  httpGet('/api/superadmin/tenants/list', query.value).then((res) => {
    if (res.data) {
      // 初始化数据
      const arr = res.data.items;
      for (let i = 0; i < arr.length; i++) {
        arr[i].create_time = dateFormat(arr[i].create_time)
      }
      console.log("res.data",arr)
      dealers.value.items = arr
      dealers.value.total = res.data.total
      dealers.value.page = res.data.page
      dealer.value.page_size = res.data.page_size
    }
    loading.value = false
  }).catch(() => {
    ElMessage.error('加载用户列表失败')
  })
}

const handleSearch = () => {
  fetchDealerList(dealers.value.page, dealers.value.page_size)
}

// 禁用用户
const removeDealer = function (dealer) {
  ElMessageBox.confirm(
      '此操作将会禁用经销商，确认操作吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    dealer.Status =1
    httpPost('/api/superadmin/tenants/update', dealer).then((res) => {
      ElMessage.success('操作成功！')
    }).catch((e) => {
      ElMessage.error('操作失败，' + e.message)
    })
  }).catch(() => {
    ElMessage.info('操作被取消')
    console.log("11==>",dealer)
  })

}

const dealerEdit = function (row) {
  dealer.value = row
  title.value = '编辑经销商'
  showDealerEditDialog.value = true
  add.value = false
}

const addDealer = () => {
  dealer.value = {}
  title.value = '添加经销商'
  showDealerEditDialog.value = true
  add.value = true
}

const saveDealer = function () {
  dealerEditFormRef.value.validate((valid) => {
    if (valid) {
      showDealerEditDialog.value = false
     if (dealer.value.Id) {
    
      httpPost('/api/superadmin/tenants/update', dealer.value).then((res) => {
        ElMessage.success('操作成功！')
        if (add.value) {
          dealers.value.items.push(res.data)
        }
      }).catch((e) => {
        ElMessage.error('操作失败，' + e.message)
      })
    }else{
      dealer.value.DatabaseName = `root:Bandacloud2023@!@tcp(180.101.182.53:3306)/${dealer.value.DatabaseName}?charset=utf8&parseTime=True&loc=Local`;
     console.log("==>",dealer.value.DatabaseName)
      httpPost('/api/superadmin/tenants/save', dealer.value).then((res) => {
        ElMessage.success('操作成功！')
        if (add.value) {
          dealers.value.items.push(res.data)
        }
      }).catch((e) => {
        ElMessage.error('操作失败，' + e.message)
      })
    }
     
    } else {
      return false
    }
  })
}

const handleSelectionChange = function (rows) {
  // TODO: 批量禁用操作
  console.log(rows)
}

//弹窗组件
// const dealerDialogRef = ref(null);

// const handleOpenDialog = () => {
//   dealerDialogRef.value?.handleOpen();
// };
const resetPass = (row) => {
  dealer.value = row
  showResetPassDialog.value = true
  pass.value.dealername = row.Username
}

const doResetPass = (row) => {
  dealer.value.Password = pass.value.Password;

  httpPost('/api/superadmin/tenants/update', dealer.value).then(() => {
    ElMessage.success('密码修改成功！');
    showResetPassDialog.value = false;
  }).catch((e) => {
    ElMessage.error('密码修改失败：' + e.message);
  });
}
//开启消耗统计弹窗
const countConsume = () => {
  showCountConsumeDialog.value = true
}
//日期格式转化函数
const formatTime = (timeString) => {
  const date = new Date(timeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 监听timeRange变化
watch(
      () => timeRange.value,
      async (newTimeRange, oldTimeRange) => {
        if (newTimeRange && Array.isArray(newTimeRange) && newTimeRange.length === 2) {
     

      const startTime = formatTime(newTimeRange[0]);
      const endTime = formatTime(newTimeRange[1]);

          try {
            const res = await httpPost('/api/superadmin/tenants/totalCallsCount', {
              start_time: startTime,
              end_time: endTime,
            });
            EchartsData.value = res.data;
          } catch (error) {
            ElMessage.error("请求失败");
          }
        }
      },
      { immediate: true } 
    );
    // 超管是否需要次数限制
//     const getAllocCalls = () => {
//   httpGet('/api/admin/dashboard/stats').then((res) => {
//     allocCalls.value = res.data.allocCalls
//   }).catch((e) => {
//     ElMessage.error('获取失败，' + e.message)
//   })
// }
const distribute = (row) => {
  showDistributeDialog.value = true
  distributeData.value.id = row.Id
  distributeData.value.username = row.Username
  distributeData.value.calls = row.TotalCalls
  console.log("===>",row)
}

const doDistribute = () => {
  if(distributeData.value.distributeMethod === 0){
    distributeData.value.amount = -Math.abs(distributeData.value.amount)
  }
  
  httpPost('/api/superadmin/tenants/divideCallsToAdmin', {tenantId:distributeData.value.id,num:distributeData.value.amount}).then(() => {
    ElMessage.success('操作成功！')
    closeDistributeDialog()
    fetchDealerList(dealers.value.page, dealers.value.page_size)
    // getAllocCalls()
  }).catch((e) => {
    ElMessage.error('操作失败，' + e.message)
  })
}
const closeDistributeDialog = () => {
  showDistributeDialog.value = false
  distributeData.value.amount = ""
}
</script>

<style lang="stylus" scoped>
.dealer-list {

  .handle-box {
    .handle-input {
      max-width 150px;
      margin-right 10px;
    }
  }

  .table {
    width 100%
  }

  .opt-box {
    padding-bottom: 10px;

    .el-icon {
      margin-right: 5px;
    }
  }

  .el-select {
    width: 100%
  }
  .count-consum-time{
    margin-left:8px;
    margin-bottom: 20px;
  }
  .count-consum-time-picker{
    margin-right:20px;
    display: inline-block
  }

}
</style>